package com.forlove.app.qselect.answer.ui;

import android.Manifest;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.PermissionsChecker;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.FriendManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadContactsAsync;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.answer.entity.AnswerEntity;
import com.forlove.app.qselect.answer.entity.BatchInfoEntity;
import com.forlove.app.qselect.answer.presenter.CircleGuidePresenter;
import com.forlove.app.qselect.answer.view.CircleGuideView;
import com.forlove.app.qselect.friend.entity.FriendEntity;
import com.forlove.app.qselect.friend.entity.MineFriendEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.ContactsInfoEntityList;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.ui.ChoiceNewAgeActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

/**
 * 圈选引导页
 * 在该页面需要先把通讯录和题目获取到后才能跳转至投票页面
 * Created by yjl on 2017/10/19.
 */

@RuntimePermissions
public class CircleGuideActivity extends BaseActivity implements View.OnClickListener,
        LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>, CircleGuideView {


    @BindView(R.id.bt_next_step)
    TextView bt_next_step;

    @BindView(R.id.sim_fre)
    SimpleDraweeView sim_fre;

    private List<ContactsInfoEntity> contactsInfoEntities = new ArrayList<>();
    private List<MineFriendEntity> mineFriendEntities = new ArrayList<>();
    private List<MineFriendEntity> recomendFriend = new ArrayList<>(); //返回的推荐好友
    private LoadContactsAsync async;
    private AnswerEntity answerEntity;
    private boolean toCircle = false;  //点击了进入圈一圈
    private CircleGuidePresenter circleGuidePresenter;
    private UserEntity userEntity;
    private boolean qyqFriendFlag = false; //标志是否获取到了圈一圈好友
    private boolean contactsFlag = false;
    private boolean recommendFlag = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_circle_guide;
    }

    @Override
    public void initView() {
        initContact();
        circleGuidePresenter = new CircleGuidePresenter(this);
        setPresenter(circleGuidePresenter);
        if (!UserManager.getUserLoginState(this)) {
            Toast.makeText(this, "请先登录!", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, ChoiceNewAgeActivity.class));
            this.finish();
        }
        initGif();
        userEntity = UserManager.getUesrInfo(this);
        mineFriendEntities.addAll(FriendManager.getFriends(this));
        if (mineFriendEntities.size() == 0) {
            qyqFriendFlag = false;
            circleGuidePresenter.loadFriendListData();
        } else {
            qyqFriendFlag = true;
        }
        circleGuidePresenter.loadQuestionData(userEntity);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_next_step:
                toCircle = true;
                if (answerEntity != null) {
                    checkContact();
                } else {
                    circleGuidePresenter.loadQuestionData(userEntity);
                }
                break;
        }
    }

    private void initGif() {
        DraweeController mDraweeController = Fresco.newDraweeControllerBuilder().setAutoPlayAnimations(true)
                //设置uri,加载本地的gif资源
                .setUri(Uri.parse("res://" + getPackageName() + "/" + R.mipmap.add_friend_guide))//设置uri
                .build();
        //设置Controller
        sim_fre.setController(mDraweeController);
        sim_fre.setVisibility(View.VISIBLE);
    }

    private void checkContact() {
        if (this.answerEntity == null) {
            return;
        }
        BatchInfoEntity batchInfoEntity = this.answerEntity.batchInfo;
        if (this.answerEntity.expire > 0) {
            //判断限制条件
            Intent intent = new Intent(this, LimitAnswerActivity.class);
            Bundle bundle = new Bundle();
            bundle.putLong(LimitAnswerActivity.KEY_EXPIRE_TIME, this.answerEntity.expire);
            if (batchInfoEntity != null) {
                bundle.putInt(LimitAnswerActivity.KEY_CIRCLE_NUM, batchInfoEntity.note_times);
            }
            intent.putExtras(bundle);
            startActivity(intent);
            this.finish();
        } else {
            Intent intent = new Intent(this, AnswerSubjectActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("answer", this.answerEntity.serializeToString());
            intent.putExtras(bundle);
            startActivity(intent);
            this.finish();
        }
    }

    private void initContact() {
        if (PermissionsChecker.getInstance().
                lacksPermission(this, android.Manifest.permission.READ_CONTACTS)) {
            CircleGuideActivityPermissionsDispatcher.needContactsWithPermissionCheck(this);
        } else {
            ContactsInfoEntityList infoEntityList = new ContactsInfoEntityList();
            infoEntityList.parseJSONString(ContactsManager.getSaveContactsFriend(this));
            if (infoEntityList.contactsInfoEntities.size() > 0) {
                contactsFlag = true;
                contactsInfoEntities.addAll(infoEntityList.contactsInfoEntities);
            } else {
                getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, this);
            }
        }

        //通讯录监听
        ContentObserver contentObserver = new ContentObserver(new Handler()) {
            @Override
            public boolean deliverSelfNotifications() {
                return super.deliverSelfNotifications();
            }

            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
                getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, CircleGuideActivity.this);
            }

            @Override
            public void onChange(boolean selfChange, Uri uri) {
                super.onChange(selfChange, uri);
            }
        };
        Uri uri = Uri.parse("content://com.android.contacts/data");
        getContentResolver().registerContentObserver(uri, true, contentObserver);
    }

    private LoadContactsAsync createContacts() {
        if (async == null) {
            async = new LoadContactsAsync(this);
        }
        return async;
    }


    @Override
    public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
        return createContacts();
    }

    @Override
    public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
        UserEntity userEntity = UserManager.getUesrInfo(this);
        if (userEntity != null) {
            if (!TextUtils.isEmpty(userEntity.userMobile)
                    && data != null
                    && data.size() > 0) {
                data.remove(userEntity.userMobile);
            }
        }
        contactsFlag = true;
        contactsInfoEntities.clear();
        contactsInfoEntities.addAll(data);
        //保存本地通讯录
        ContactsManager.saveContactsFriend(this, data);
        loadFriends();
    }

    @Override
    public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {
        //   LogUtil.e("yjl", "onLoaderReset");
    }

    @Override
    public void updateAnswerView(AnswerEntity answerEntity) {
        if (answerEntity == null) {
            return;
        }
        this.answerEntity = answerEntity;
        recomendFriend.clear();
        recomendFriend.addAll(answerEntity.recomandFriend);
        if (recomendFriend.size() > 0) {
            for (MineFriendEntity friendEntity : recomendFriend) {
                friendEntity.isRecomend = true;
            }
        }
        recommendFlag = true;
        loadFriends();
        if (toCircle) {
            checkContact();
        }
    }

    private void loadFriends() {
        if (contactsFlag && qyqFriendFlag && recommendFlag) {
            List<MineFriendEntity> entities = FriendManager.getSubjectCandidate(recomendFriend, mineFriendEntities, contactsInfoEntities, -1);
            if (entities != null && entities.size() < 4) {
                bt_next_step.setText("添加好友");
                bt_next_step.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toMainActivity(MainActivity.POSITION_FRIEND);
                    }
                });
            } else {
                bt_next_step.setText("开始圈一圈");
                bt_next_step.setOnClickListener(this);
            }

        }
    }

    @Override
    protected void onDestroy() {
        getSupportLoaderManager().destroyLoader(LoadContactsAsync.ASYNC_ID);
        super.onDestroy();
    }

    @Override
    public void updateFriendListView(List<FriendEntity> friendEntityList) {
        mineFriendEntities.clear();
        mineFriendEntities.addAll(friendEntityList);
        qyqFriendFlag = true;
        loadFriends();
    }

    @NeedsPermission(Manifest.permission.READ_CONTACTS)
    void needContacts() {
        getSupportLoaderManager().restartLoader(LoadContactsAsync.ASYNC_ID, null, CircleGuideActivity.this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CircleGuideActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied(Manifest.permission.READ_CONTACTS)
    void refuseContacts() {
        Toast.makeText(this, "拒绝了同步通讯录", Toast.LENGTH_SHORT).show();
        contactsFlag = true;
    }

    @OnNeverAskAgain(Manifest.permission.READ_CONTACTS)
    void failGetContacts() {
        contactsFlag = true;
    }
}


